package com.hrbu.mp.generator.config;



import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import java.util.EnumSet;

/**
 * @Description: WebConfig类用于替换Web.xml配置文件，作为web项目的配置类
 * @Author: tanyajun
 * @CreateTime: 2021/3/19
 * @Blog: https://tanyajun.top
 */
// 实现WebApplicationInitializer接口并重写方法

public class WebConfig implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        // 注册SpringMVC配置类
        context.register(SrpingMVCConfig.class);
        context.setServletContext(servletContext);
        // 配置监听器
        //servletContext.addListener(XXXXX);
        // 配置字符编码过滤器
        servletContext.addFilter("encoding",
                new CharacterEncodingFilter("UTF-8", true, true))
        .addMappingForUrlPatterns(this.getDispatcherTypes(),false,"/*");
        // 配置核心控制器
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        // 添加上下文路径地址
        servlet.addMapping("/");
        // 设置启动级别
        servlet.setLoadOnStartup(1);
    }
    private boolean isAsyncSupported() {
        return true;
    }

    private EnumSet<DispatcherType> getDispatcherTypes() {
        return isAsyncSupported() ?
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) :
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);
    }
}


